import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Header } from './layout/Header';
import { Sidebar } from './layout/Sidebar';
import { AppRoutes } from './AppRoutes';
import { useGlobalError } from '@/stores/hooks';

export const Layout: React.FC = () => {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const { hasError, error, clearError } = useGlobalError();
  const location = useLocation();

  // 检查是否为登录/注册页面
  const isAuthPage = ['/login', '/register'].includes(location.pathname);
  const isErrorPage = ['/404', '/unauthorized'].includes(location.pathname);

  // 如果是认证页面或错误页面，直接渲染路由内容
  if (isAuthPage || isErrorPage) {
    return <AppRoutes />;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 全局错误提示 */}
      {hasError && (
        <div className="fixed top-0 left-0 right-0 z-50 bg-red-600 text-white px-4 py-3">
          <div className="flex items-center justify-between max-w-7xl mx-auto">
            <span className="text-sm">{error}</span>
            <button
              onClick={clearError}
              className="text-white hover:text-gray-200"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* 头部导航 */}
      <Header />

      <div className="flex">
        {/* 侧边栏 */}
        <Sidebar 
          isOpen={sidebarOpen} 
          onClose={() => setSidebarOpen(false)} 
        />

        {/* 主内容区域 */}
        <main className="flex-1 lg:ml-64">
          {/* 移动端菜单按钮 */}
          <div className="lg:hidden bg-white border-b border-gray-200 px-4 py-3">
            <button
              onClick={() => setSidebarOpen(true)}
              className="text-gray-500 hover:text-gray-700"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>
          </div>

          {/* 页面内容 */}
          <div className="p-4 lg:p-8">
            <AppRoutes />
          </div>
        </main>
      </div>
    </div>
  );
};